<?php
declare (strict_types=1);

namespace app\common\model;

use think\Model;
use think\facade\Db;

class Statistics extends Model
{
    public static function _update($amount, $key): void
    {
        $info = parent::where('key', $key)->find();
        $info->today += $amount;
        $info->month += $amount;
        $info->year += $amount;
        $info->sum += $amount;
        $info->save();
    }

    /**
     * 更新统计
     * 定时
     */
    public static function _timing(): array
    {
        parent::startTrans();
        try {
            $m = date('m');
            $d = date('d');
            if ($m == '01' && $d == '01') {
                Db::execute('update `statistics` set `yesterday` = `today`, `last_month` = `month`, `last_year` = `year`, `today` = 0, `month` = 0, `year` = 0');
            } elseif ($d == '01') {
                Db::execute('update `statistics` set `yesterday` = `today`, `last_month` = `month`, `today` = 0, `month` = 0');
            } else {
                Db::execute('update `statistics` set `yesterday` = `today`, `today` = 0');
            }
            Db::execute('update `user` set `always_day` = 0 where `is_day_sign` = 0');
            Db::execute('update `user` set `is_day_sign` = 0 where `is_day_sign` = 1');

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write('logs/statistics.log', $e->getMessage());

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '更新成功'];
    }
}